package com.dmai.capacity.platform.user.controller;

import com.dmai.capacity.platform.common.dto.PageResult;
import com.dmai.capacity.platform.common.dto.ResponseEntity;
import com.dmai.capacity.platform.common.model.LoginAppUser;
import com.dmai.capacity.platform.common.model.SysUser;
import com.dmai.capacity.platform.constants.RoleTypeEnum;
import com.dmai.capacity.platform.oauth.common.util.AuthUtils;
import com.dmai.capacity.platform.user.pojo.request.PasswordEmailRequest;
import com.dmai.capacity.platform.user.pojo.request.PasswordResetRequest;
import com.dmai.capacity.platform.user.pojo.response.InstitutionSimpleVO;
import com.dmai.capacity.platform.user.pojo.response.InstitutionVO;
import com.dmai.capacity.platform.user.pojo.response.SysRoleVO;
import com.dmai.capacity.platform.user.pojo.response.SysUserVO;
import com.dmai.capacity.platform.user.service.ISysInstitutionService;
import com.dmai.capacity.platform.user.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 作者 ftquan E-mail: 464725602@qq.com
 * @version 创建时间：2017年11月12日 上午22:57:51
 * 用户
 */
@Slf4j
@RestController
public class SysUserController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysInstitutionService institutionService;

    @Autowired
    private PasswordEncoder passwordEncoder;


    /**
     * 忘记密码发邮件
     */
    //    @PreAuthorize("hasAuthority('user:get/users')")
    @PostMapping("/users/forgotPassword")
    public ResponseEntity sendPasswordResetEmail(@RequestBody @Valid PasswordEmailRequest item) {

        boolean b = userService.sendPasswordResetEmail(item);
        return ResponseEntity.succeed(b, "操作成功");
    }


    /**
     * 重置密码
     *
     * @return true 数据验证通过， false 数据校验失败
     */
    //    @PreAuthorize("hasAuthority('user:get/users')")
    @PutMapping("/users/resetPassword")
    public ResponseEntity resetPassword(@RequestBody @Valid PasswordResetRequest item) {

        boolean b = userService.resetPassword(item);
        return ResponseEntity.succeed(b, "操作成功");
    }


    /**
     * 当前登录用户 LoginAppUser
     *
     * @return
     */
    @GetMapping("/users/current")
    public ResponseEntity getLoginAppUser() {
        SysUserVO user = new SysUserVO();
        try {
            LoginAppUser loginUser = AuthUtils.getLoginAppUser();
            user.setId(loginUser.getId());
            user.setUsername(loginUser.getUsername());
            user.setRealname(loginUser.getRealname());
            user.setMobile(loginUser.getMobile());
            user.setEmail(loginUser.getEmail());
            user.setCreateTime(loginUser.getCreateTime());
            user.setHeadImgUrl(loginUser.getHeadImgUrl());
            user.setType(loginUser.getType());
            user.setDescription(loginUser.getDescription());
            if (CollectionUtils.isNotEmpty(loginUser.getRoles())) {
                user.setRoles(loginUser.getRoles().stream().map(r -> new SysRoleVO(r.getCode(), r.getName())
                ).collect(Collectors.toList()));
            }
            user.setRoleIds(loginUser.getRoleIds());
            if (RoleTypeEnum.INSTITUTION.getCode().equals(user.getType())) {

                InstitutionVO institution = institutionService.findById(Long.valueOf(loginUser.getOrganizationId()));
                if (institution != null) {
                    InstitutionSimpleVO institutionVO = new InstitutionSimpleVO(institution.getId(), institution.getCode(), institution.getName(), institution.getExamVenue());
                    user.setOrganizationId(institution.getExamVenue());
                    user.setInstitution(institutionVO);
                }
            } else {
                user.setOrganizationId(loginUser.getOrganizationId());
            }
            user.setTenantId(loginUser.getTenantId());
        } catch (Exception e) {
            log.error(e.toString());
            log.error("获取登陆用户失败:{}", e);

            return ResponseEntity.failed("获取登陆用户失败");
        }

        return ResponseEntity.succeed(user);
    }

    @GetMapping(value = "/users-anon/login", params = "username")
    public LoginAppUser findByUsername(String username) {
        return userService.findByUsername(username);
    }


    @PreAuthorize("hasAuthority('user:get/users/{id}')")
    @GetMapping("/users/{id}")
    public LoginAppUser findUserById(@PathVariable(value = "id") Long id) {
        return userService.findByUserId(id);
    }

    @GetMapping("/users/getName")
    public ResponseEntity getName(@RequestParam(value = "keyValue") String keyValue) {
        LoginAppUser user = userService.findByUsername(keyValue);
        return ResponseEntity.succeed(user == null ? "" : user.getRealname(), "获取成功！");
    }


    @PreAuthorize("hasAuthority('user:get/users/{id}')")
    @GetMapping("/users/findUserByIds")
    public ResponseEntity<List<LoginAppUser>> findUserByIds(@RequestParam String keyValue) {
        String[] idArray = keyValue.split(",");
        List<LoginAppUser> userList = new ArrayList<>();
        for (String userId : idArray) {
            userList.add(userService.findByUserId(Long.valueOf(userId)));
        }
        return ResponseEntity.succeed(userList);
    }


    /**
     * 修改用户
     *
     * @param sysUser
     */
    @PreAuthorize("hasAuthority('user:put/users/me')")
    @PutMapping("/users")
    public void updateSysUser(@RequestBody SysUser sysUser) {
        userService.update(sysUser);
    }


    /**
     * 用户查询
     * http://192.168.3.2:7000/users?access_token=3b45d059-601b-4c63-85f9-9d77128ee94d&start=0&length=10
     *
     * @param params
     * @return
     */
    @PreAuthorize("hasAuthority('user:get/users')")
    @GetMapping("/users")
    public PageResult<SysUser> findUsers(@RequestParam Map<String, Object> params) {
        return userService.findUsers(params);
    }


    @PreAuthorize("hasAuthority('user:get/users')")
    @GetMapping("/users/existsName")
    public ResponseEntity existsName(@RequestParam(value = "userName") String userName) {
        LoginAppUser user = userService.findByUsername(userName);
        return ResponseEntity.succeed(user != null);
    }


    /**
     * 校验密码
     */
    @GetMapping(value = "/users/validatePassword")
    public ResponseEntity validatePassword(@RequestParam(value = "password") String password) {
        LoginAppUser sysUser = AuthUtils.getLoginAppUser();
        if (StringUtils.isBlank(password)) {
            throw new IllegalArgumentException("密码不能为空");
        }
        if (sysUser.getId().equals("1")) {
            return ResponseEntity.failed("超级管理员不给予修改");
        }
        if (!passwordEncoder.matches(password, sysUser.getPassword())) {
            return ResponseEntity.failed("密码错误");
        } else {
            return ResponseEntity.succeed("校验成功");
        }
    }

    /**
     * 修改密码
     */
    @PatchMapping(value = "/users/password")
    public ResponseEntity updatePassword(@RequestBody SysUser sysUser) {
        LoginAppUser currentUser = AuthUtils.getLoginAppUser();
        if (StringUtils.isBlank(sysUser.getOldPassword())) {
            throw new IllegalArgumentException("旧密码不能为空");
        }
        if (StringUtils.isBlank(sysUser.getNewPassword())) {
            throw new IllegalArgumentException("新密码不能为空");
        }
        boolean success = userService.updatePassword(currentUser.getId(), sysUser.getOldPassword(), sysUser.getNewPassword());
        if (success) {
            return ResponseEntity.succeed("操作成功");
        } else {
            return ResponseEntity.failed("操作失败");
        }
    }


    /**
     * 更新用户状态
     *
     * @param id
     * @author gitgeek
     */
    @PreAuthorize("hasAuthority('user:post/users/{id}/updateStatus' )")
    @PostMapping(value = "/users/{id}/updateStatus")
    public ResponseEntity updateStatus(@PathVariable(value = "id") Long id, Boolean enabled) {
        if (id.equals("1")) {
            return ResponseEntity.failed("超级管理员不允许禁用");
        }
        userService.updateEnabled(id, enabled);
        return ResponseEntity.succeed(null, "更新成功");
    }


    /**
     * 给用户重置密码
     *
     * @param id
     * @author gitgeek
     */
    @PreAuthorize("hasAuthority('user:post/users/{id}/resetPassword' )")
    @PostMapping(value = "/users/{id}/resetPassword")
    public ResponseEntity resetPassword(@PathVariable(value = "id") Long id) {
        if (id.equals("1")) {
            return ResponseEntity.failed("超级管理员不给予修改");
        }
        boolean success = userService.updatePassword(id, null, "123456");
        if (success) {
            return ResponseEntity.succeed("操作成功");
        } else {
            return ResponseEntity.failed("操作失败");
        }
    }


    /**
     * 删除人员
     * delete /users/1
     *
     * @param id
     */
    @PreAuthorize("hasAuthority('user:delete/users/{id}')")
    @DeleteMapping("/users/{id}")
    public ResponseEntity delete(@PathVariable(value = "id") Long id) {
        try {
            userService.delUser(id);
            return ResponseEntity.succeed("操作成功");
        } catch (Exception e) {
            log.error(e.toString());

            return ResponseEntity.failed("操作失败");
        }
    }


}
